package com.yuncheng.spcyApi.busService.exam.service;

import com.yuncheng.spcyApi.busService.exam.constant.QuestionTypeEnum;
import com.yuncheng.spcyApi.busService.exam.vo.ParseQuestionRules;
import com.yuncheng.spcyApi.busService.exam.vo.QuestionInfoVo;
import com.yuncheng.spcyApi.busService.exam.vo.QuestionItem;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 方式一：正则表达
 *      缺点：不能正确提取内容，部分题目提取特征不明显
 * 方式二：逐行读取+正则表达
 *
 * @author ：hua
 * @description：解析题目文本
 */
public class ParseQuestionTextUtils {
    private static final Logger log = LoggerFactory.getLogger(ParseQuestionTextUtils.class);

    /** 选项分割排序 */
    static final String[] letterList = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    /** 大标题规则 */
//    static final String dbtRule = "([一二三四五六]+、[\\u4e00-\\u9fa5]+题)\\（每题(\\d+)分）";
//    static final String dbtRule = "([一二三四五六]+、[\\u4e00-\\u9fa5]+题)\\每题(\\d+)分";
    static final String dbtRule = "(\\S+题)\\（每题(\\d+)分）";

    /** 获取选项中第一个字符 */
    public static String getOptionFirstChar(String options, char gjz){
        String firstChar = StringPatternUtils.indexFirstStringWithChar(options, gjz);
        if (Arrays.asList(letterList).contains(firstChar)){
            return firstChar;
        }

        return options;
    }

    /** 解析文本-生成题目及选项 */
    public static List<QuestionInfoVo> parse(String text, ParseQuestionRules rule){

        String divisionRule=rule.getDivisionRule();
//        String questionRule=rule.getQuestionRule();
        String answerRule=rule.getAnswerRule();
        String optionRule=rule.getOptionRule();
        //1.把文本分割成单独的题目
        String[] questionInfoStr = text.split(divisionRule);
        //2.遍历题目文本
        QuestionInfoVo questionInfo;
        List<QuestionInfoVo> list=new ArrayList<>();
        QuestionTypeEnum type = QuestionTypeEnum.SIGNAL_CHOICE;

        /** 题目类型分数 */
        Matcher dbtMatcher = Pattern.compile(dbtRule, Pattern.MULTILINE).matcher(text);
        Map<String, String> dbtScoreMap = new HashMap<>();
        while (dbtMatcher.find()) {
            // 获取题目类型
            String questionType = null;
            // 获取分数
            String score = null;
            try {
                questionType = dbtMatcher.group(1);
                score = dbtMatcher.group(2).trim();
            }catch (Exception e){
                log.error("大标题：{}", e.getMessage());
            }

            if (StringUtils.isBlank(questionType) || StringUtils.isBlank(score)){
                continue;
            }

            String dbtType = null;
            if (questionType.contains(QuestionTypeEnum.SIGNAL_CHOICE.getLabel())) {
                dbtType = QuestionTypeEnum.SIGNAL_CHOICE.getLabel();
            }else if (questionType.contains(QuestionTypeEnum.MULTIPLE_CHOICE.getLabel())) {
                dbtType = QuestionTypeEnum.MULTIPLE_CHOICE.getLabel();
            }else if (questionType.contains(QuestionTypeEnum.JUDGMENTAL.getLabel())) {
                dbtType = QuestionTypeEnum.JUDGMENTAL.getLabel();
            }else if (questionType.contains(QuestionTypeEnum.COMPLETION.getLabel())) {
                dbtType = QuestionTypeEnum.COMPLETION.getLabel();
            }else if (questionType.contains(QuestionTypeEnum.SUBJECTIVE.getLabel())) {
                dbtType = QuestionTypeEnum.SUBJECTIVE.getLabel();
            }else {
                dbtType = QuestionTypeEnum.SUBJECTIVE.getLabel();
            }

            if (!dbtScoreMap.containsKey(dbtType)) {
                log.info("类型分数：{}:{}", dbtType, score);
                dbtScoreMap.put(dbtType, score);
            }

        }

        /** 题目及选项解析 */
        for (String str : questionInfoStr) {
            if(str.isEmpty()){
                continue;
            }

//            log.info("题目信息=>"+str);

            questionInfo=new QuestionInfoVo();
            Pattern pattern= Pattern.compile(answerRule);

            // 现在创建 matcher 对象
            /** 2.1 提取答案 */
            Matcher matcher = pattern.matcher(str);
            List<String>answerList=new ArrayList<>();
            if(matcher.find()){
                answerList=Arrays.stream(matcher.group(1).split(rule.getAnswerSplit())).collect(Collectors.toList());
            }
//            log.info("答案=>"+answerList);

            /** 2.1.1 把去掉字符中的答案去了 */
            str=str.replaceAll(answerRule,"");
//            log.info("去答案后题目信息=>"+str);

            /** 2.2 提取全部选项字符 */
            List<String> optionList=Arrays.stream(str.split(optionRule)).collect(Collectors.toList());
            /*Matcher optionMatcher = Pattern.compile(optionRule).matcher(str);
            List<String> optionList = new ArrayList<>();
            while (optionMatcher.find()){
                optionList.add(matcher.group(1).trim()); // 添加匹配到的选项到列表中，并去除前后空格
            }*/

            /** 2.3.提取题目 */
            questionInfo.setId(UUID.randomUUID().toString());
            if (CollectionUtils.isEmpty(optionList)){
                continue;
            }
            questionInfo.setContent(optionList.get(0));

//            log.info("题目=>"+optionList.get(0));
            optionList.remove(0);

//            log.info("选项=>"+optionList);
            if(StringUtils.isBlank(questionInfo.getContent())){
                continue;
            }

            /** 2.4 确定题型 */
            if(optionList.isEmpty()){
                if(answerList.size()==1){
                    type=QuestionTypeEnum.SUBJECTIVE;
                }else{
                    type=QuestionTypeEnum.COMPLETION;
                }
            }else{
                if(answerList.size()==1){
                    if(optionList.size()==2){
                        type=QuestionTypeEnum.JUDGMENTAL;
                    }else{
                        type=QuestionTypeEnum.SIGNAL_CHOICE;
                    }
                }else{
                    type=QuestionTypeEnum.MULTIPLE_CHOICE;
                }
            }

            /** 2.4.1 确认题目分数 */
            if (dbtScoreMap.containsKey(type.getLabel())){
                questionInfo.setScore(dbtScoreMap.get(type.getLabel()));
            }else {
                if (type == QuestionTypeEnum.SUBJECTIVE){
                    questionInfo.setScore(dbtScoreMap.get(QuestionTypeEnum.JUDGMENTAL.getLabel()));
                }
            }
            questionInfo.setType(type);

            /** 2.5 获取题目选项 */
            questionInfo.setOptions(getItem(type, answerList, optionList, questionInfo.getId()));

            list.add(questionInfo);
        }

        return list;
    }

    /** 解析题目选项 */
    private static List<QuestionItem> getItem(QuestionTypeEnum type, List<String> answerList, List<String> optionList, String tmid){
        List<QuestionItem> list=new ArrayList<>();

        /** 填空题、主观题 */
        if(type==QuestionTypeEnum.SUBJECTIVE||type==QuestionTypeEnum.COMPLETION){
            list=answerList.stream().filter(i-> StringUtils.isNotBlank(i)).map(i->{
                QuestionItem item=new QuestionItem();
                item.setAnswer(i);

                item.setQuestionId(tmid);
                item.setId(UUID.randomUUID().toString());

                return item;
            }).collect(Collectors.toList());

            /** 单选、多选 */
        }else if(type==QuestionTypeEnum.SIGNAL_CHOICE||type== QuestionTypeEnum.MULTIPLE_CHOICE){

            /** 提取答案字符 */
            List<String> temAnswerList = answerList.stream()
                    .map(e -> {
                return e.replaceAll("\\r|\\n|\\s", "").toUpperCase();
            }).collect(Collectors.toList());

            /** 获取字母的下标 */
            list = IntStream.rangeClosed(0, optionList.size()-1)
                    .filter(i -> StringUtils.isNotBlank(optionList.get(i)))
                    .mapToObj(i->{

                        QuestionItem item=new QuestionItem();
                        item.setContent(optionList.get(i).trim());

                        item.setQuestionId(tmid);
                        item.setId(UUID.randomUUID().toString());

                        /** 确定题目选项答案，1即为答案，空值默认非答案 */
                        boolean contains = temAnswerList.contains(letterList[i]);
                        if(contains){
        //                    log.error("正确答案");
                            item.setAnswer("1");
                        }
                        return item;
            }).collect(Collectors.toList());


        }else if(type==QuestionTypeEnum.JUDGMENTAL){
            /** 判断题不做处理，当前判断题即为填空题格式解析 */
//            System.out.println("_______________________________________________");
        }
        return list;
    }

}


